package com.woniuxy.controller;

import java.io.File;
import java.io.IOException;
import java.security.Principal;

import org.apache.shiro.subject.Subject;

import java.util.Arrays;

import java.util.Date;
import java.util.List;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.bind.annotation.RestController;

import com.woniuxy.entity.Secutity;
import com.woniuxy.entity.User;
import com.woniuxy.handler.MyExceptionHandler;
import com.woniuxy.service.UserService;
import com.woniuxy.utils.ResultUtil;

@RestController
@RequestMapping("/user")
public class UserController extends MyExceptionHandler {
	@Autowired

	UserService userService;

	/*
	 * @Autowired UserServiceImpl userService;
	 */

	@RequestMapping("/login") // 这个请求会被shiro拦截

	@ResponseBody
	public ResultUtil<Object> login(User user, String code, HttpServletRequest request) {
		System.out.println(user.getAccount());
		System.out.println(user.getPassword());
		System.out.println(code);
		// 新建结果对象，给网页返回判断的结果
		ResultUtil<Object> resultUtil = new ResultUtil<>();

		// 获取验证码
		String input_code = request.getParameter("code");
		String create_code = (String) request.getSession().getAttribute("code");
		// 进行验证
		boolean result = input_code.equalsIgnoreCase(create_code);

		if (!result) {
			// 验证失败
			resultUtil.setStatus(ResultUtil.ERROR);
			resultUtil.setMessage("验证码错误");
			// 直接返回，不再进行账号密码判断
			return resultUtil;
		}

		// 认证登录，查询用户去色信息，根据角色显示内容

		// 1 获取到subject 对象，当前浏览器，验证用户是否登录
		Subject cuSubject = SecurityUtils.getSubject();
		// 2 判断是否认证
		if (!cuSubject.isAuthenticated()) {

			// 从网页得到用户输入的密码，使用MD5加密

			// 从网页得到用户输入的密码，使用MD5加密

			String pwd = new SimpleHash("MD5", user.getPassword(), user.getAccount(), 512).toString();
			// 没认证，也就是没登录，创建令牌(携带账号密码)，进行账号密码判定
			UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), pwd);

			// 认证
			try {
				cuSubject.login(token);// 去MyRealm里面去进行认证
				// 不报异常
				System.out.println("认证成功");
				// 根据角色跳转到指定页面
				resultUtil.setStatus(ResultUtil.SUCCESS);

				// 普通用户跳转到首页

				// 普通用户跳转到首页

			} catch (UnknownAccountException e) {
				System.out.println("账号不存在");
				return resultUtil.setStatus(ResultUtil.ERROR).setMessage("账号不存在");
				// TODO: handle exception
			} catch (IncorrectCredentialsException e) {
				System.out.println("密码错误");
				return resultUtil.setStatus(ResultUtil.ERROR).setMessage("账号或者密码错误");
				// TODO: handle exception
			} catch (Exception e) {
				System.out.println("其他异常");
				// TODO: handle exception
			}

		} else {
			return resultUtil.setStatus(ResultUtil.ERROR).setMessage("重复登录");
		}

		return resultUtil;
	}

	@RequestMapping("/regist")
	@ResponseBody
	public ResultUtil<Object> regist(User user, String code, HttpServletRequest request) {
		ResultUtil<Object> resultUtil = new ResultUtil<>();

		System.err.println("dasdas" + user);
		// 获取验证码
		String input_code = request.getParameter("code");
		String create_code = (String) request.getSession().getAttribute("code");
		// 进行验证
		boolean result = input_code.equalsIgnoreCase(create_code);

		if (!result) {
			// 验证失败
			resultUtil.setStatus(ResultUtil.ERROR);
			resultUtil.setMessage("验证码错误");
			// 直接返回，不再进行账号密码判断
		}
		// 根据账户去数据库查询，是否包含此账户
		User user2 = userService.findByAccount(user.getAccount());

		if (user2 != null) {
			resultUtil.setStatus(ResultUtil.ERROR);
			resultUtil.setMessage("账户已存在");
		} else {
			// 对密码进行加密
			String password = new SimpleHash("MD5", user.getPassword(), user.getAccount(), 512).toString();
			user.setPassword(password).setHead("afsafs").setRegtime(new Date()).setStatus(0);			
			boolean addUser= userService.addUser(user);
			boolean addRoles = userService.addUserRoles(user.getAccount());
			
			if (!addUser) {
				resultUtil.setStatus(ResultUtil.ERROR).setMessage("注册异常");
				System.err.println("方法异常");
			
			}else {
            System.out.println("+++++++++++++++++添加用户");
			System.err.println(">>>>>>" + user);
			resultUtil.setStatus(ResultUtil.SUCCESS).setMessage("注册成功");
			

			}

		}
		return resultUtil;
	}

	// 判断角色
	@RequestMapping("/judgeRole")
	@ResponseBody
	public void judageRole() {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute("user");

	}

	// 动态页面，放到templates这个文件夹里
	@RequestMapping("/center")
	public ModelAndView center(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView();
		// 从当前session获取账户信息
		// 这个方法没有效果User user = (User) SecurityUtils.getSubject().getPrincipal();
		Principal principal = request.getUserPrincipal();
		User user = new User().setAccount(principal.getName());
		// User user = new User().setAccount("wangwu");
		modelAndView.addObject("user", user);
		System.out.println(">>>>>>" + user.getAccount());

		modelAndView.setViewName("/center.html");
		return modelAndView;
	}

	// zzj

	// 通过id查找用户信息
	@RequestMapping("/find")
	@ResponseBody
	public User find() {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute("user");

		return userService.find(user.getU_id());
	}

	// 更改密码
	@RequestMapping("/updatepassword")
	@ResponseBody
	public int updatepwd(String oldpwd, String newpwd) {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute("user");

		return userService.updatepwdbyuid(user.getU_id(), oldpwd, newpwd,user.getAccount());

	}

	// 更改用户资料
	@RequestMapping("/upinfo")
	@ResponseBody
	public int upinfo() {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute("user");

		return userService.upinfo(user);

	}

	// 更换头像方法
	@RequestMapping("/upload")
	@ResponseBody
	public String uploadImage(@RequestParam("headImg") MultipartFile image, HttpServletRequest request)
			throws IllegalStateException, IOException {
		/*
		 * // 项目根路径 String p = request.getServletContext().getRealPath("");
		 * System.out.println(p); File app = new File(p); // 获取上级目录 // 在上级目录下创建存放图片的文件夹
		 * File img = new File(app, "img"); if (!img.exists()) { img.mkdirs(); }
		 * 
		 * // 获取文件名 String fileName = image.getOriginalFilename(); String prefix =
		 * fileName.substring(fileName.lastIndexOf(".") + 1);
		 * 
		 * // UUID String name = UUID.randomUUID().toString(); fileName = name + "." +
		 * prefix; // 新路径 File newFile = new File(img, fileName); // 保存文件
		 * image.transferTo(newFile); // 将文件url放入数据库中 userService.updateHeadImg(new
		 * User().setU_id(2).setHead("img/" + fileName)); return ("img/" + fileName);
		 */
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User)session.getAttribute("user");
		String fileName = image.getOriginalFilename();
		String path = request.getServletContext().getRealPath("upload");
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		String newpath = "/home/files/";
		fileName = UUID.randomUUID().toString()+fileName;
		newpath = newpath+fileName;
		System.out.println(newpath);
		file = new File(newpath);
		userService.updateHeadImg(new User().setU_id(user.getU_id()).setHead(newpath));
		image.transferTo(file);
		return (newpath);

	}

	
	// 找回密码的方法
	@RequestMapping("secutity")
	@ResponseBody
	public ResultUtil<String> findPasswordBysecutity(String question, String answer) {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute("user");

		ResultUtil<String> result = new ResultUtil<>();
		String an = userService.findPasswordBysecutityquestion(question, user.getU_id(), answer);
		if (an != null) {
			result.setData(an);
			result.setStatus(ResultUtil.SUCCESS);
		} else {
			result.setStatus(ResultUtil.ERROR);
		}
		return result;

	}

	// 查找该用户的所有密保问题
	@RequestMapping("/findsecutity")
	@ResponseBody
	public List<Secutity> findsecutity() {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute("user");

		return userService.findquestion(user.getU_id());
	}

	// 修改密保问题
	@RequestMapping("tsecutity")
	@ResponseBody
	public int setsecutity(String question, String answer, String newquestion, String password) {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute("user");
		String pwd = userService.findpwdbyuid(user.getU_id());
		password = new SimpleHash("MD5", password, user.getAccount(), 512).toString();
		if (pwd != null) {
			if (pwd.equals(password)) {
				int i = userService.setsecurity(question, answer, user.getU_id(), newquestion);
				return i;
			}
		}
		return -1;

	}

	// 增加密保问题
	@RequestMapping("/addsecutity")
	@ResponseBody
	public int addsecutity(String password, String question, String answer) {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		User user = (User) session.getAttribute("user");
		password = new SimpleHash("MD5", password, user.getAccount(), 512).toString();
		System.out.println("进入方法");
		String pwd = userService.findpwdbyuid(user.getU_id());
		
		if (pwd != null) {
			if (pwd.equals(password)) {
				if (userService.findSecutityCount(user.getU_id()) >= 3) {
					System.out.println(000);
					return 0;
				} else {
					return userService.addsecutity(question, answer, user.getU_id());
				}

			}
		}
		return -1;
	}

	// wzh
	@RequestMapping("/personalCenter")
	// 前端向后端发送请求进入个人中心
	public ModelAndView center() {
		ModelAndView modelAndView = new ModelAndView();
		// 先获取当前登录的对象
		User user = new User();
		user.setAccount(user.getAccount());
		modelAndView.addObject("User", user);
		modelAndView.setViewName("/personalCenter.html");
		return modelAndView;

	}

	@RequestMapping("/allUser")
	public ResultUtil<Object> allUser(int pageNum, int pageSize) {
		ResultUtil<Object> resultUtil = new ResultUtil<>();
		resultUtil.setData(userService.allUser(pageNum, pageSize));
		resultUtil.setStatus(ResultUtil.SUCCESS);
		return resultUtil;
	}

	@RequestMapping("/batchUpdateUsers")
	public ResultUtil<Object> batchUpdateUsers(int status, String ids) {
		// 转换成int[]
		String[] idStrings = ids.split(",");
		int[] idsArray = new int[idStrings.length];
		for (int j = 0; j < idStrings.length; j++) {
			idsArray[j] = Integer.parseInt(idStrings[j]);
		}
		// System.out.println(Arrays.toString(idsArray));

		ResultUtil<Object> resultUtil = new ResultUtil<>();
		int result = userService.batchUpdateUsers(status, idsArray);
		resultUtil.setData(result);
		if (result > 0) {
			resultUtil.setStatus(ResultUtil.SUCCESS);
		} else {
			resultUtil.setStatus(ResultUtil.ERROR);
		}
		return resultUtil;
	}

	@RequestMapping("/batchDeleteUsers")
	public ResultUtil<Object> batchDeleteUsers(String ids) {
		// 转换成int[]
		String[] idStrings = ids.split(",");
		int[] idsArray = new int[idStrings.length];
		for (int j = 0; j < idStrings.length; j++) {
			idsArray[j] = Integer.parseInt(idStrings[j]);
		}

		System.out.println(Arrays.toString(idsArray));

		ResultUtil<Object> resultUtil = new ResultUtil<>();
		int result = userService.batchDeleteUsers(idsArray);
		resultUtil.setData(result);
		if (result > 0) {
			resultUtil.setStatus(ResultUtil.SUCCESS);
		} else {
			resultUtil.setStatus(ResultUtil.ERROR);
		}

		return resultUtil;
	}
	
	@ResponseBody
	@RequestMapping("/findUser")
	public User findUser() {
		   Subject subject = SecurityUtils.getSubject();
		   Session session = subject.getSession();
		   User user = (User) session.getAttribute("user");
		   System.out.println(user);
		   return user;
	}
	

}
